package com.fallsvc.common.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.io.UnsupportedEncodingException;
import java.util.Optional;

/**
 * @auther falls_vc
 * description:
 * @date 2025/9/26  11:34
 */
public class MailUtil {
    private JavaMailSender javaMailSender;

    private MailProperties mailProperties;

    public MailUtil(JavaMailSender javaMailSender,MailProperties mailProperties) {
        this.javaMailSender = javaMailSender;
        this.mailProperties = mailProperties;
    }

    public void send(String to,String subject,String content) throws MessagingException, UnsupportedEncodingException {
        // 创建一个邮件消息
        MimeMessage message = javaMailSender.createMimeMessage();

        // 创建 MimeMessageHelper
        MimeMessageHelper helper = new MimeMessageHelper(message, false);


        String personal = Optional.ofNullable(mailProperties.getProperties().get("personal"))
                .orElse(mailProperties.getUsername());
        // 发件人邮箱和名称
        helper.setFrom(mailProperties.getUsername(), personal);
        // 收件人邮箱
        helper.setTo(to);
        // 邮件标题
        helper.setSubject(subject);
        // 邮件正文，第二个参数表示是否是HTML正文
        helper.setText(content, true);

        // 发送
        javaMailSender.send(message);
    }
}
